#!/usr/bin/env python3
# vim:fileencoding=utf-8

'''
express.js 的 wrapper
'''

import os
import sys
import re
import time
import subprocess
import select
from functools import lru_cache
from subprocess import getoutput
from myutils import restart_if_failed
from checktime import TimeChecker

logfname = os.path.expanduser('~/etc/log/express.access.log')
http_ip = re.compile(r'^(\d{1,3}\.){3}\d{1,3}')

def main(app, files):
  if app.find('/') != -1:
    os.chdir(os.path.split(app)[0])
  else:
    app = './' + app
  try:
    tc = TimeChecker(files)
    with open(logfname, 'a', buffering=1) as log:
      restart_if_failed(runapp, 10, args=(app, tc, log))
  except KeyboardInterrupt:
    print('退出。')

@lru_cache(maxsize=20)
def lookupip(ip):
  print('cip called')
  return getoutput('cip ' + ip).replace('CZ88.NET', '').strip() or '-'

def logAddIP(m):
  ip = m.group(0)
  return '%s (%s)' % (ip, lookupip(ip))

def runapp(app, tc, logfile):
  p = subprocess.Popen(app, bufsize=1, stdout=subprocess.PIPE)
  try:
    poll = select.poll()
    poll.register(p.stdout, select.POLLIN)
    while True:
      f = poll.poll(2000)
      if f:
        l = p.stdout.readline()
        if not l:
          print('Error!', file=sys.stderr)
          break
        log = l.rstrip().decode()
        log = http_ip.sub(logAddIP, log)
        print(log)
        print(log, file=logfile)
      if tc.check():
        poll.unregister(p.stdout)
        p.terminate()
        p.wait()
        print('重新载入...')
        time.sleep(1)
        break
  finally:
    try:
      p.terminate()
      p.wait()
    except:
      pass

  # wait for re-run
  raise Exception

if __name__ == '__main__':
  if len(sys.argv) >= 2:
    app = sys.argv[1]
    files = sys.argv[1:]
  else:
    app = 'app.js'
    files = 'app.js'

  main(app, files)

